# -*- coding: utf-8 -*-
#   基础的delegate
# @Time    ： 2023/1/30  17:46
# @Auther  ： 徐良
# File     :  baseDelegate.py

import re

from PySide6.QtWidgets import QStyledItemDelegate, QStyleOptionButton, QStyle, QApplication
from PySide6.QtCore import Qt, Signal, QModelIndex
from PySide6.QtGui import QDoubleValidator, QIntValidator
from share.baseFunction import quote, getListFormStrByVLine, getInstanceType
from share.sqlFunction import getSWO
from share.dataFactory import DataFactory


class BaseDelegate(QStyledItemDelegate):
    mesDataChanged = Signal(QModelIndex)
    afterF7Enter = Signal(QModelIndex)

    def __init__(self):
        super(BaseDelegate, self).__init__()
        self.index = QModelIndex
        self.color = None
        self.statusFieldName = None
        self.colorGroup = None
        self.model = None
        self.colorGroup = ''

    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

    def setAlignMent(self, dic, editor):
        """
        设置控件对齐方式
        :param dic: 控件相关信息
        :param editor: 控件
        """
        if dic['align'] == 'Qt.AlignLeft':
            editor.setAlignment(Qt.AlignLeft)
        elif dic['align'] == 'Qt.AlignRight':
            editor.setAlignment(Qt.AlignRight)
        elif dic['align'] == 'Qt.AlignHCenter':
            editor.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        else:
            editor.setAlignment(Qt.AlignRight)

    # 设置校验器
    def setValidator(self, dic, editor):
        # 取验证器类型、正则表达式
        validator = dic['validator']
        if validator is None or validator == '':
            return

        if validator == 'DoubleValidator':
            pDoubleValidator = QDoubleValidator(self)
            pDoubleValidator.setNotation(QDoubleValidator.StandardNotation)
            sdot = dic['decimal']
            if sdot is None or sdot == '':
                dot = 2
            else:
                dot = int(sdot)

            pDoubleValidator.setDecimals(dot)
            editor.setValidator(pDoubleValidator)

        if validator == 'IntValidator':
            pIntValidator = QIntValidator(self)
            editor.setValidator(pIntValidator)

    # 设置输入提示
    def setPlaceHolderText(self, dic, editor):
        phText = dic['placeHoderText']
        if phText:
            editor.setPlaceholderText(phText)

    # 设置combo的domain
    def setComboDomain(self, dic, editor):
        list1 = dic['domains']
        editor.addItems(list1)
        editor.setCurrentIndex(-1)

    def setComboMesDomain(self, dic, editor):
        """
        设置comboMes的domain
        :param dic:
        :param editor:
        :return:
        """
        list1 = dic['domains']
        ll = list1[2]
        editor.addItems(ll)
        editor.setCurrentIndex(-1)

    # 设置comboMes的domain
    def setComboMesDomain(self, dic, editor):
        list1 = dic['domains']
        lList = list1[2]
        editor.addItems(lList)
        editor.setCurrentIndex(-1)

    def onF7HelpDo(self):
        """
        界面上tavleView控件中f7字段回车帮助功能
        :return:
        """
        num = self.index.column()
        dic = self.work.bodyFieldInfo(num)

        def getSql(s, v):
            swd = getSWO(s)
            s = swd['s']
            r = re.search(r'a\.\w{2,}', s)
            if r is None:
                ss = s + ' where Fnumber=' + quote(v)
            else:
                ss = s + ' where a.Fnumber=' + quote(v)
            return ss

        def getValueList(sSql, fieldList):
            vList = []
            model = DataFactory.getQueryModelForSql(sql)
            rows = model.rowCount()
            if rows == 0:
                for o in fieldList:
                    vList.append('')
            else:
                for f in fieldList:
                    v = model.record(0).value(f)
                    vList.append(v)
            return vList

        def setValueToModel(fList, tList, vList, row):
            for f, t, v in zip(fList, tList, vList):
                col = self.work.bListField.index(f.lower())
                index = self.work.bodyModel.index(row, col)
                if t == 'integer':
                    v = str(v)
                self.work.bodyModel.setData(index, v, Qt.EditRole)

        def setNextColunm(nextIndex):
            self.tableView.setCurrentIndex(nextIndex)
            self.tableView.edit(nextIndex)

        if dic['isF7']:
            relationTableList = getListFormStrByVLine(dic['relationTable'])
            sql = relationTableList[4]
            relationGetAndRetList = getListFormStrByVLine(dic['relationGetAndRet'])
            getFieldList = relationGetAndRetList[0].split(',')
            FieldTypeList = relationGetAndRetList[1].split(',')
            setFieldList = relationGetAndRetList[2].split(',')
            value = self.editor.text().strip()

            sql = getSql(sql, value)
            valueList = getValueList(sql, getFieldList)
            setValueToModel(setFieldList, FieldTypeList, valueList, self.index.row())

            self.afterF7Enter.emit(self.index)

    # ****************************    方法
    def getStatus(self, row):
        """
        获取model中指定字段的值
        :param row:
        :return:
        """
        val = self.model.record(row).value(self.statusFieldName)
        if val == '' or val is None:
            return 0
        if getInstanceType(val) == 'str':
            return 1
        else:
            if self.colorGroup == 'checkBoxColor':
                if val > 1:
                    val = 1

            return val


    def getFieldValue(self, idx):
        """
        获取model中指定列的值
        :param idx:
        :return:
        """
        if self.fieldList is None:
            return ''
        fn = self.fieldList[idx.column()]
        if self.model is not None and self.model.rowCount() > 0:
            return str(self.model.record(idx.row()).value(fn))
        else:
            return ''

